function sendRequest(method, uri, data, callback) {
    const request = new XMLHttpRequest()
    request.open(method, `http://127.0.0.1:3000${uri}`)
    request.setRequestHeader('content-type', 'application/json')
    request.onreadystatechange = () => {
        if (request.readyState === 4 && request.status === 200) {
            callback(request.responseText)
        }
    }
    request.send(data ? JSON.stringify({ comment: data }) : null)
}

function getComments() {
    return new Promise((reslove, reject) => {
        sendRequest('get', '/api?api=getComments', null, res => reslove(res))
    })
}

function postData(data) {
    return new Promise((reslove, reject) => {
        sendRequest('post', '/', data, res => reslove(res))
    })
}


window.onload = () => {
    const comments = document.getElementById('comments')
    const comment = document.getElementById('comment')
    const btn = document.getElementById('btn')
    async function initPage() {
        const res = await getComments()
        const data = JSON.parse(res).content
        comments.innerHTML = data
    }


    btn.addEventListener('click', async (e) => {
        e.preventDefault()
        await postData(comment.value)
        const res = await getComments()
        const data = JSON.parse(res).content
        comments.innerHTML = data
    })
    initPage()
}